package com.ljq.yy.single;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class YSingleTest {

	public static void main(String[] args) throws InterruptedException {
		Container container = new Container();
		CountDownLatch latch = new CountDownLatch(1000);
		// 等待所有线程初执行完后再执行
		for (int i = 0; i < 1000; i++) {
			Thread t = new Thread(new SingleRunable(latch, container), "线程：" + i);
			t.start();
		}
		latch.await();

		Iterator<String> iterator = container.map.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println(key + ">>>" + container.map.get(key));

		}
		System.out.println("结束 ");

	}
}

class Container {
	public static Map<String, Integer> map = new HashMap<String, Integer>();
}

class SingleRunable implements Runnable {
	private CountDownLatch latch;
	private Container container;

	public SingleRunable(CountDownLatch latch, Container container) {
		super();
		this.latch = latch;
		this.container = container;
	}

	@Override
	public void run() {
		// 双重
		this.container.map.put("double" + YSingleDouble.getInstance().hashCode(), YSingleDouble.getInstance().hashCode());
		YSingleDouble.getInstance().say();

		// 静态内部类, 《Effective Java》上所推荐的
		this.container.map.put("double" + YSingleIn.getInstance().hashCode(), YSingleIn.getInstance().hashCode());
		YSingleIn.getInstance().say();

		// 枚举：防止反序列化
		this.container.map.put("double" + YSingleEnum.INSTANCE.hashCode(), YSingleEnum.INSTANCE.hashCode());
		YSingleEnum.INSTANCE.say();

		latch.countDown();
	}
}
